package com.navcoo.yidaaddproapi.service.serviceImpl;


import com.navcoo.yidaaddproapi.response.Result;
import com.navcoo.yidaaddproapi.pojo.dto.File.FileProperties;
import com.navcoo.yidaaddproapi.service.FileService;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 文件服务导入
 *
 * @author Navcoo
 * @date 2024-03-28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final FileProperties fileProperties;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * 上传
     *
     * @param file 文件
     * @return {@link String}
     */
    @Override
    public Result<String> upload(MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        InputStream inputStream = file.getInputStream();
        log.info("inputStream: {}", inputStream);

        String url = UUID.randomUUID() + ".png";

        String resultUrl = pushOss(inputStream, url);

        return Result.success(resultUrl);

    }


    public String pushOss(InputStream inputStream, String url) throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        String resultUrl = "";

        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpoint)
                            .credentials(accessKey, secretKey)
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket " + bucketName + " already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(url)
                            .stream(inputStream, inputStream.available(), -1)
                            .build());

            minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(url)
                    .build());

            inputStream.close();
            resultUrl = endpoint + "/" + bucketName + "/" + url;

            System.out.println("resultUrl:" + resultUrl);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }

        return resultUrl;
    }
}
